package nxu.it.movieapi.service.pg;

import nxu.it.api.model.Genre;
import nxu.it.api.service.GenreService;
import org.jdbi.v3.core.Jdbi;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class GenreServicePgImpl implements GenreService {
    final Jdbi jdbi;

    public GenreServicePgImpl(@Qualifier("createJdbi") Jdbi jdbi) {
        this.jdbi = jdbi;
    }

    @Override
    public List<Genre> findAll() {
      String sql = "SELECT id, name FROM public.genre";
        List<Genre> genreList = jdbi.withHandle(handle -> handle.createQuery(sql)
                .mapToBean(Genre.class)
                .list());
        return genreList;
    }
    @Override
    public List<Genre> findByMovieId(Integer movieId) {
        String sql = "SELECT g.id, g.name FROM public.genre g " +
                "JOIN public.movie_genre mg ON g.id = mg.genre_id " +
                "WHERE mg.movie_id = :movieId";
        return jdbi.withHandle(handle -> handle.createQuery(sql)
                .bind("movieId", movieId)
                .mapToBean(Genre.class)
                .list());
    }

    @Override
    public List<Genre> findByName(String genreName) {
        String sql = "SELECT id, name FROM public.genre WHERE name LIKE :genreName";
        return jdbi.withHandle(handle -> handle.createQuery(sql)
                .bind("genreName", "%" + genreName + "%")
                .mapToBean(Genre.class)
                .list());
    }

}
